package com.yuntsg.nnsfcp.service.front.ext;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yuntsg.nnsfcp.entity.ParseEntity;
import com.yuntsg.nnsfcp.front.entity.OrderBaseInfo;
import com.yuntsg.nnsfcp.front.entity.ParsingTxt;
import com.yuntsg.nnsfcp.front.entity.Wosdetail;
import com.yuntsg.nnsfcp.service.front.AbstractCalculateCite;
import com.yuntsg.nnsfcp.service.front.ut.PinYinUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * CSCD数据库计算被引
 *
 * @author ：ljx
 * @date ：Created in 2019/7/3
 */
@Slf4j
@Component
public class CscdCalculateCite extends AbstractCalculateCite implements Serializable {

    /**
     * 计算被引
     *
     * @param wosDetail 本地wos
     * @param boo       true 计算wos的全部被引, false不计算全部被引
     */
    @Override
    public void runCalculateCite(Wosdetail wosDetail, boolean boo) {
        List<Integer> fids = searchFileServiceImpl.getFids();
        //获取一篇文章的所有引用
        List<ParsingTxt> txtList
                = parsingTxtMapper.selectList(new QueryWrapper<ParsingTxt>()
                .in("file_id", fids));

        if (txtList.size() > 0) {
            log.info("被引次数计算中..");

            //获取用户选择的哪一种排引方式
            OrderBaseInfo orderBaseInfo
                    = orderBaseInfoMapper.selectOne(new QueryWrapper<OrderBaseInfo>()
                    .eq("apply_id", wosDetail.getCommissionid()));
            String citationStatus = orderBaseInfo.getCitationStatus();

            //委托人名字的 九种变体
            String authorNameEn = orderBaseInfo.getAuthorNameEn();
            String[] userAuthorArr
                    = authorNameEn
                    .toLowerCase()
                    .replaceAll(" ", "")
                    .replaceAll(",", "")
                    .replaceAll("-", "").trim()
                    .split(";");

            //作者的三种排除方式
            if (citationStatus != null && (!"".equals(citationStatus))) {
                //1:排除作者本人外(默认),
                if ("1".equals(citationStatus) || boo) {
                    log.info("1:排除作者本人外");
                    selfCite = 0;
                    totleList = new ArrayList<>();
                    selfCiteList = new ArrayList<>();
                    citedList = new ArrayList<>();
                    wosQuoteList = new ArrayList<>();

                    for (ParsingTxt parsingTxt : txtList) {
                        //取出抓下来的 au字段英文作者
                        String[] auSplit = new String[0];
                        if (parsingTxt.getAu() != null) {
                            String au = parsingTxt.getAu().toLowerCase().replace(" ", "").trim();
                            //判断是否是中文,是中文转换成英文做匹配
                            /*if (PinYinUtil.isChinese(au)) {
                                au = PinYinUtil.getEnName(au).replace(" ", "").trim();
                            }*/
                            if (au.contains(";")) {
                                auSplit = au.split(";");
                            } else {
                                auSplit = new String[]{au};
                            }
                        }
                        boolean auboo = false;
                        //匹配自引英文名
                        if (userAuthorArr.length > 0) {
                            for (int j = 0; j < userAuthorArr.length; j++) {
                                if (auSplit.length > 0) {
                                    //自引-匹配AU
                                    if (Arrays.asList(auSplit).contains(userAuthorArr[j])) {
                                        auboo = true;
                                        break;
                                    }
                                }
                            }
                            if (!boo) {
                                //添加总引列表
                                ParseEntity parseEntity1 = addParse(parsingTxt);
                                totleList.add(parseEntity1);
                            }
                            if (auboo) {
                                if (!boo) {
                                    //包含则自引+1
                                    selfCite += 1;
                                    ParseEntity parseEntity = addParse(parsingTxt);
                                    selfCiteList.add(parseEntity);
                                }
                            } else {
                                //他引
                                ParseEntity parseEntity = addParse(parsingTxt);
                                if (!boo) {
                                    citedList.add(parseEntity);
                                } else {
                                    //wos的总被引计算
                                    wosQuoteList.add(parseEntity);
                                }
                            }
                        }
                    }
                }
                // 2:排除所有作者,
                else if ("2".equals(citationStatus)) {
                    log.info("2:排除所有作者");
                    totleList = new ArrayList<>();
                    eliminateAllList = new ArrayList<>();
                    wosQuoteList = new ArrayList<>();

                    //拿到这篇文章的全部作者 , 有中文 & 有英文.
                    String author = wosDetail.getAuthor();
                    if (author != null) {
                        //英文;中文
                        String[] authorEnCn = author.replace(" ", "").trim().split("&");
                        //文章中的英文
                        String[] en = new String[0];
                        //文章中的中文 == 有可能没有
                        String[] cn = new String[0];
                        if (authorEnCn.length == 2) {
                            en = authorEnCn[0]
                                    .toLowerCase()
                                    .replaceAll(" ", "")
                                    .replaceAll(",", "")
                                    .replaceAll("-", "")
                                    .split(";");
                            cn = authorEnCn[1].split(";");
                        } else if (authorEnCn.length == 1) {
                            en = authorEnCn[0]
                                    .toLowerCase()
                                    .replaceAll(" ", "")
                                    .replaceAll(",", "")
                                    .replaceAll("-", "")
                                    .split(";");
                        } else {
                            log.error("CSCD _ 没有作者信息");
                        }

                        //匹配
                        for (ParsingTxt parsingTxt : txtList) {
                            //引用 = 英文名
                            String[] auSplit = new String[0];
                            if (parsingTxt.getAu() != null) {
                                String au = parsingTxt.getAu()
                                        .toLowerCase()
                                        .replaceAll(" ", "")
                                        .replaceAll(",", "")
                                        .replaceAll("-", "")
                                        .trim();
                                if (au.contains(";")) {
                                    auSplit = au.split(";");
                                } else {
                                    auSplit = new String[]{au};
                                }
                            }
                            //引用 = 中文名
                            String[] z2Split = new String[0];
                            if (parsingTxt.getZ2() != null) {
                                String z2 = parsingTxt.getZ2()
                                        .toLowerCase()
                                        .replaceAll(" ", "")
                                        .replaceAll(",", "")
                                        .replaceAll("-", "")
                                        .trim();
                                if (z2.contains(";")) {
                                    z2Split = z2.split(";");
                                } else {
                                    z2Split = new String[]{z2};
                                }
                            }

                            boolean boo1 = true;
                            //匹配英文
                            if (en.length > 0) {
                                if (auSplit.length > 0) {
                                    for (int i = 0; i < en.length; i++) {
                                        if (Arrays.asList(auSplit).contains(en[i])) {
                                            boo1 = false;
                                            break;
                                        }
                                        //匹配中文
                                        else if (cn.length > 0) {
                                            if (z2Split.length > 0) {
                                                for (int k = 0; k < cn.length; k++) {
                                                    if (Arrays.asList(auSplit).contains(en[i])) {
                                                        boo1 = false;
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            System.out.println("=====111111===========" + boo);
                            if (!boo) {
                                //添加总引列表
                                ParseEntity parseEntity1 = addParse(parsingTxt);
                                totleList.add(parseEntity1);
                            }
                            if (boo1) {
                                ParseEntity parseEntity = addParse(parsingTxt);
                                if (!boo) {
                                    eliminateAllList.add(parseEntity);
                                } else {
                                    //wos的总被引计算
                                    wosQuoteList.add(parseEntity);
                                }
                            }
                        }
                    }
                }// 3:排除项目合作者
                else if ("3".equals(citationStatus)) {
                    log.info(" 3:排除项目合作者");
                    totleList = new ArrayList<>();
                    collaboratorsList = new ArrayList<>();
                    wosQuoteList = new ArrayList<>();

                    //1.得到文章中的全部作者
                    String author = wosDetail.getAuthor();
                    //2.得到用户输入的全部作者
                    String userTeam = orderBaseInfo.getAuthorNameEn();
                    //3.比较
                    if (author != null && userTeam != null) {
                        String[] authorArr = new String[0];
                        // & = 中文模式下存在中文和英文的作者名, 抓取下来时候 英文 & 中文, & 分隔了
                        if (author.contains("&")) {
                            author = author.split("&")[0];
                            authorArr = author.split("&")[0].toLowerCase().replace(" ", "").split(";");
                        } else {
                            authorArr = author.toLowerCase().replace(" ", "").split(";");
                        }
                        String[] userTeams = userTeam.toLowerCase().replace(" ", "").split(";");

                        wosDetail.setTeamAuthorCheck("0");
                        for (int i = 0; i < authorArr.length; i++) {
                            if (Arrays.asList(authorArr).contains(userTeams[i])) {
                                wosDetail.setTeamAuthorCheck("1");
                                break;
                            }
                        }

                        //3.将用户作者 与 文章的完整作者 拼接(并去重)
                        StringBuilder authorBuilder = new StringBuilder();
                        authorBuilder.append(author);
                        if (author.contains(";")) {
                            String[] split = author.split(";");
                            for (String team : userTeams) {
                                if (Arrays.asList(split).contains(team)) {
                                    authorBuilder.append(team).append(";");
                                }
                            }
                        } else {
                            String[] str = {author};
                            for (String team : userTeams) {
                                if (Arrays.asList(str).contains(team)) {
                                    authorBuilder.append(team).append(";");
                                }
                            }
                        }
                        userTeams = authorBuilder.toString().toLowerCase().replace(" ", "").split(";");
                        log.info("<团队模式&中>文章作者+用户团队作者: " + Arrays.toString(userTeams));
                        for (ParsingTxt parsingTxt : txtList) {
                            //取出抓下来的 au字段英文作者
                            String[] auSplit = new String[0];
                            if (parsingTxt.getAu() != null) {
                                String au = parsingTxt.getAu().toLowerCase().replace(" ", "").trim();
                                //判断是否是中文,是中文转换成英文做匹配
                                if (PinYinUtil.isChinese(au)) {
                                    au = PinYinUtil.getEnName(au).replace(" ", "").trim();
                                }
                                auSplit = au.split(";");
                            }
                            boolean auboo = false;
                            //匹配自引英文名
                            if (userTeams.length > 0) {
                                for (int j = 0; j < userTeams.length; j++) {
                                    if (auSplit.length > 0) {
                                        //自引-匹配AU
                                        if (Arrays.asList(auSplit).contains(userTeams[j])) {
                                            auboo = true;
                                        }
                                    }
                                }
                                if (!boo) {
                                    //添加总引列表
                                    ParseEntity parseEntity1 = addParse(parsingTxt);
                                    totleList.add(parseEntity1);
                                }
                                //添加合作者列表
                                if (!auboo) {
                                    ParseEntity parseEntity = addParse(parsingTxt);
                                    if (!boo) {
                                        collaboratorsList.add(parseEntity);
                                    } else {
                                        //wos的总被引计算
                                        wosQuoteList.add(parseEntity);
                                    }
                                }
                            }
                        }
                    }
                }
                if (boo) {
                    //wos的总被引次数
                    if (wosQuoteList != null && wosQuoteList.size() > 0) {
                        wosDetail.setWosCitedNum(txtList.size());
                        wosDetail.setWosHeCitedNum(wosQuoteList.size());
                        wosDetail.setWosHeCitedList(JSON.toJSONString(wosQuoteList));
                    }
                } else {
                    //总被引列表 & 总被引次数
                    if (totleList != null && totleList.size() > 0) {
                        wosDetail.setUserTotalQuoteNum(txtList.size());
                        wosDetail.setUserTotalQuoteList(JSON.toJSONString(totleList));
                    }
                    //排除文章中的所有作者
                    if (eliminateAllList != null && eliminateAllList.size() > 0) {
                        //列表
                        wosDetail.setEliminateAllList(JSON.toJSONString(eliminateAllList));
                        //次数
                        wosDetail.setEliminateAllNum(eliminateAllList.size());
                    }
                    //合作者引用次数 & 合作者列表
                    if (collaboratorsList != null && collaboratorsList.size() > 0) {
                        wosDetail.setTeamNum(collaboratorsList.size());
                        wosDetail.setTeamList(JSON.toJSONString(collaboratorsList));
                    }
                    //作者本人外的他引次数//判断作者外的他引(总引 - 自引)== 默认勾选的
                    if (txtList.size() > 0 && citedList.size() > 0) {
                        wosDetail.setOtherNum(txtList.size() - selfCite);
                        //作者本人外的他引列表
                        wosDetail.setOtherList(JSON.toJSONString(citedList));
                    }
                    //自引列表自引列表
                    if (selfCiteList.size() > 0) {
                        wosDetail.setMyQuote(JSON.toJSONString(selfCiteList));
                    }
                }
                wosdetailMapper.updateById(wosDetail);
                log.info("计算完成");

                //删除相关计算依赖数据
                deleteCitedTxt(txtList);
            } else {
                //删除相关计算依赖数据
                deleteCitedTxt(txtList);
                //出错处理
                myHandlerException(wosDetail);
            }
        } else {
            //删除相关计算依赖数据
            deleteCitedTxt(txtList);
            txtList = null;
            //出错处理
            myHandlerException(wosDetail);
        }
        //删除相关计算依赖数据
        deleteCitedTxt(txtList);
    }
}


